<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import request from '../../utils/sj-request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'

// 定义props
const props = defineProps({
  subjectId: {
    type: Number,
    required: true
  },
  readonly: {
    type: Boolean,
    default: false
  }
})

// 题型列表数据
const questionTypeList = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 加载状态
const loading = ref(false)
// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 新增/编辑题型对话框显示状态
const dialogVisible = ref(false)
// 是否为编辑模式
const isEdit = ref(false)
// 表单数据
const questionTypeForm = reactive({
  id: null,
  name: '',
  description: ''
})
// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入题型名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
  ]
}
// 表单引用
const formRef = ref()

// 获取所有题型
const fetchQuestionTypes = async () => {
  loading.value = true
  try {
    const res = await request({
      url: '/question-type/list',
      method: 'get'
    })
    
    if (res.code === 200) {
      questionTypeList.value = res.data || []
      pagination.value.total = questionTypeList.value.length
    } else {
      ElMessage.error(res.message || '获取题型列表失败')
    }
  } catch (error) {
    console.error('获取题型列表失败:', error)
    ElMessage.error('获取题型列表失败')
  } finally {
    loading.value = false
  }
}

// 过滤后的题型列表
const filteredQuestionTypes = computed(() => {
  if (!searchKeyword.value) {
    return questionTypeList.value
  }
  return questionTypeList.value.filter(type => 
    type.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
    (type.description && type.description.toLowerCase().includes(searchKeyword.value.toLowerCase()))
  )
})

// 打开新增题型对话框
const openAddDialog = () => {
  dialogVisible.value = true
  isEdit.value = false
  // 重置表单
  questionTypeForm.id = null
  questionTypeForm.name = ''
  questionTypeForm.description = ''
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  isEdit.value = false
  questionTypeForm.id = null
  questionTypeForm.name = ''
  questionTypeForm.description = ''
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        const res = await request({
          url: isEdit.value ? `/question-type` : '/question-type',
          method: isEdit.value ? 'put' : 'post',
          data: {
            id: isEdit.value ? questionTypeForm.id : undefined,
            name: questionTypeForm.name,
            description: questionTypeForm.description
          }
        })
        
        if (res.code === 200) {
          ElMessage.success(isEdit.value ? '编辑题型成功' : '添加题型成功')
          dialogVisible.value = false
          fetchQuestionTypes() // 刷新列表
        } else {
          ElMessage.error(res.message || (isEdit.value ? '编辑题型失败' : '添加题型失败'))
        }
      } catch (error) {
        console.error(isEdit.value ? '编辑题型失败:' : '添加题型失败:', error)
        ElMessage.error(isEdit.value ? '编辑题型失败' : '添加题型失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 编辑题型
const handleEditQuestionType = (questionType) => {
  if (questionType.name === '单选题' || questionType.name === '多选题') {
    ElMessage.warning('系统默认题型，无法操作！')
    return
  }
  isEdit.value = true
  dialogVisible.value = true
  questionTypeForm.id = questionType.id
  questionTypeForm.name = questionType.name
  questionTypeForm.description = questionType.description || ''
}

// 删除题型
const handleDeleteQuestionType = async (questionType) => {
  if (questionType.name === '单选题' || questionType.name === '多选题') {
    ElMessage.warning('系统默认题型，无法操作！')
    return
  }
  try {
    await ElMessageBox.confirm(`确定要删除题型「${questionType.name}」吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await request({
      url: `/question-type/${questionType.id}`,
      method: 'delete'
    })

    if (res.code === 200) {
      ElMessage.success('删除题型成功')
      fetchQuestionTypes() // 刷新列表
    } else {
      // 处理删除失败的情况，例如题型正在被使用
      if (res.code === 400 && res.message.includes('正在被试题使用')) {
        ElMessage.error('该题型正在被试题使用，无法删除')
      } else if (res.code === 400 && res.message.includes('正在被组卷方案使用')) {
        ElMessage.error('该题型正在被组卷方案使用，无法删除')
      } else {
        ElMessage.error(res.message || '删除题型失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除题型失败:', error)
      ElMessage.error('删除题型失败')
    }
  }
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
}

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
}

// 处理重置筛选条件
const handleReset = () => {
  searchKeyword.value = ''
  pagination.value.currentPage = 1
}

// 组件挂载时获取题型列表
onMounted(() => {
  fetchQuestionTypes()
})
</script>

<template>
  <div class="question-type-management">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchKeyword"
            placeholder="题型名称/描述"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 题型列表 -->
    <el-card class="list-container" shadow="never">
      <template #header>
        <div class="card-header">
          <span>题型列表</span>
          <el-button type="primary" @click="openAddDialog" :disabled="props.readonly">新增题型</el-button>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="filteredQuestionTypes.slice((pagination.currentPage - 1) * pagination.pageSize, pagination.currentPage * pagination.pageSize)"
        border
        style="width: 100%"
      >
        <el-table-column label="序号" width="80">
          <template #default="{$index}">
            {{ (pagination.currentPage - 1) * pagination.pageSize + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="题型名称" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{row}">
            <el-button link type="primary" size="small" @click="handleEditQuestionType(row)" :disabled="props.readonly">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDeleteQuestionType(row)" :disabled="props.readonly">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredQuestionTypes.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑题型对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑题型' : '新增题型'"
      width="30%"
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="questionTypeForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="题型名称" prop="name">
          <el-input v-model="questionTypeForm.name" placeholder="请输入题型名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="questionTypeForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入题型描述" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.question-type-management {
  width: 100%;
}

.filter-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>